package com.csxy.xxm.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.xxm.entity.EduSubject;
import com.csxy.xxm.entity.excel.SubjectData;
import com.csxy.xxm.entity.vo.OneSubject;
import com.csxy.xxm.entity.vo.TwoSubject;
import com.csxy.xxm.exception.MyException;
import com.csxy.xxm.listener.SubjectExcelListener;
import com.csxy.xxm.mapper.EduSubjectMapper;
import com.csxy.xxm.service.EduSubjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService{
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        // 1.查询所有一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id", "0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);

        // 2.查询所有二级分类
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id", "0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo);
        // 3.创建list集合，用于最终封装数据
        List<OneSubject> finaSubjectList = new ArrayList<>();
        // 4.封装一级分类
        for (int i = 0; i < oneSubjectList.size(); i++) {
            // 获取每个一级分类
            EduSubject oSubject = oneSubjectList.get(i);
            // 创建一级分类
            OneSubject oneSubject = new OneSubject();
            // 复制数据
            BeanUtils.copyProperties(oSubject, oneSubject);

            finaSubjectList.add(oneSubject);

            ArrayList<TwoSubject> finaTwoSubjectList = new ArrayList<>();

            for (int j = 0; j < twoSubjectList.size(); j++) {
                EduSubject tSubject = twoSubjectList.get(j);

                if (tSubject.getParentId().equals(oSubject.getId())) {

                    TwoSubject twoSubject = new TwoSubject();

                    BeanUtils.copyProperties(tSubject, twoSubject);
                    finaTwoSubjectList.add(twoSubject);
                }
            }
            oneSubject.setChildren(finaTwoSubjectList);
        }
        return finaSubjectList;
    }

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        try {
            InputStream is = file.getInputStream();

            EasyExcel.read(is, SubjectData.class, (ReadListener) new SubjectExcelListener(eduSubjectService))
                        .sheet().doRead();

        }catch (Exception e){
            throw new MyException(20001,"excel文件读取异常");
        }
    }
}
